package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.LikesBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LikesBehaviorServiceImpl implements LikesBehaviorService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 点赞
     * @param dto
     */
    @Override
    public ResponseResult likeArticle(LikesBehaviorDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = ApThreadLocalUtil.getApUser();
        if(apUser == null && apUser.getId() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 获取key
        String redisKey = "USER_LIKES_"+dto.getArticleId();
        Boolean likeFlag = stringRedisTemplate.opsForHash().hasKey(redisKey, apUser.getId().toString());
        if(likeFlag && dto.getOperation()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已经赞过了");
        }
        if(likeFlag && dto.getOperation()==1){
            // 已关注,并且要取消关注
            // 删除redis数据
            stringRedisTemplate.opsForHash().delete(redisKey, apUser.getId().toString());
            // 删除数据库数据
            Query query = Query.query(
                    Criteria.where("userId").is(apUser.getId()).and("articleId").is(dto.getArticleId())
            );
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }
        // 没有关注的情况
        if(!likeFlag && dto.getOperation()==0){
            //新增到redis
            stringRedisTemplate.opsForHash().put(redisKey, apUser.getId().toString(),"1");
            // 新增到数据库
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setUserId(apUser.getId().longValue());
            apLikesBehavior.setType((short) 0);
            mongoTemplate.save(apLikesBehavior);
        }
        return ResponseResult.okResult("成功");
    }
}
